import axios from 'axios'
import storage from 'store'
import router from "@/config/router"
import { ACCESS_TOKEN } from "./index"
import { showToast } from 'vant'

const service = axios.create({
    baseURL: process.env.VUE_APP_API_BASE_URL,
    method: 'post',
    timeout: 6000
})

const err = (error)=>{
    if (error.response) {
        const data = error.response.data
        if (error.response.status === 401) {
          showToast('登录已失效')
          router.replace('/login')
        } else {
          showToast(data.msg || '系统异常')
        }
      }
      return Promise.reject(error)
}

service.interceptors.request.use(config=>{
    const token = storage.get(ACCESS_TOKEN)
    if(token){
        config.headers['token'] = token
    }
    return config
}, err)

service.interceptors.response.use(response =>{
    const {code, msg, data} = response.data
    if(code !== '0000'){
        showToast(msg || '系统异常')
        return Promise.reject(msg)
    }
    return data
},err)

export default service